<template>
  <div class="details">
    <van-nav-bar title="个人资料" left-arrow @click-left="onClickLeft">
      <template #left>
        <van-icon name="arrow-left" color="#a8a9aa" size="18" />
      </template>
    </van-nav-bar>
    <van-form @submit="onSubmit">
      <div class="panel">
        <div class="content">
          <div class="label">头像</div>
          <div class="input-box">
            <van-field name="userAvatar">
              <template #input>
                <van-uploader :after-read="afterRead">
                  <van-image
                    round
                    width="80"
                    height="80"
                    fit="cover"
                    :src="userInfoTemp.userAvatar"
                  />
                </van-uploader>
              </template>
            </van-field>
          </div>
        </div>
      </div>
      <div class="panel">
        <div class="content">
          <div class="label">昵称</div>
          <div class="input-box">
            <van-field
              v-model="userInfoTemp.userName"
              name="userName"
              input-align="right"
              @blur="userNameBlur"
            />
          </div>
        </div>
      </div>
      <div class="panel">
        <div class="content">
          <div class="label">账号</div>
          <div class="input-box">
            {{ userInfoTemp.account }}
          </div>
        </div>
      </div>
      <div class="panel">
        <div class="content">
          <div class="label">个性签名</div>
          <div class="input-box">
            <van-field
              v-model="userInfoTemp.individualitySignature"
              name="individualitySignature"
              input-align="right"
            />
          </div>
        </div>
      </div>
      <div class="panel">
        <div class="content">
          <div class="label">邮箱</div>
          <div class="input-box">
            {{ userInfoTemp.userEmail }}
          </div>
        </div>
      </div>
      <div class="panel">
        <div class="content">
          <div class="label">性别</div>
          <div class="input-box">
            <van-field
              readonly
              clickable
              name="sex"
              input-align="right"
              :value="getSexChinese"
              @click="sexInput.showPicker = true"
            />
            <van-popup v-model="sexInput.showPicker" position="bottom">
              <van-picker
                show-toolbar
                :columns="sexInput.columns"
                @confirm="onConfirm"
                @cancel="sexInput.showPicker = false"
              />
            </van-popup>
          </div>
        </div>
      </div>
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >保存</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import { uploaderAvatar, updateUserInfo } from '@/api/userApi';
export default {
  created() {
    this.userInfoTemp = Object.assign({}, this.userInfo); // 深拷贝
  },
  data() {
    return {
      sexInput: {
        value: "男",
        columns: ["男", "女"],
        showPicker: false,
        isUploadAvatar: false, // 判断是否修改了图片
      },
      userInfoTemp: {},
    };
  },
  methods: {
    ...mapMutations("m_user", ["setUserInfo"]),
    onClickLeft() {
      this.$emit("onBackBase");
    },
    async onSubmit(values) {
      // 发送请求时需要手动加上 id
      // values.userId = this.userInfo.userId;
      // values.userAvatar = this.userInfoTemp.avatarUpload;
      delete values.userAvatar;
      values.sex = this.userInfoTemp.sex; // 改成服务器需要的string

      // 只修改图片
      // let { data: res } = await this.$http.post(
      //   "/api/user/info/update/avatar",
      //   {
      //     avatar: values.userAvatar,
      //   }
      // );
      // let res1 = await uploaderAvatar(values.userAvatar);
      let promises = [updateUserInfo(values)];
      if(this.isUploadAvatar) {
        promises.push(uploaderAvatar(this.userInfoTemp.avatarUpload));
      }
      let res = await Promise.all(promises);
      console.log(res);
      let isOk = res.every((item) => {
        if(item.data.code === 200 && item.data.success === true) {
          return true
        }
      })
      if (isOk) {
        this.userInfoTemp = res[0].data.data; // 先赋值第一个返回值
        if(res[1]) {
          // 如果存在图片上传的情况就覆替换掉userAvatar
          this.userInfoTemp.userAvatar = res[1].data.data
        }
        this.setUserInfo(this.userInfoTemp);
        this.$notify({
          type: "success",
          message: "修改成功",
        });
        let token = this.$jwt.sign(
          this.userInfoTemp,
          this.$appConfig.jwt_secret
        );
        localStorage.setItem("token", token);
        this.onClickLeft();

        // 清楚掉标志
        this.isUploadAvatar = false;
      } else {
        this.$notify({
          type: "danger",
          message: "修改失败",
        });
      }
    },
    onConfirm(value) {
      this.userInfoTemp.sex = value === this.sexInput.columns[0] ? 'FEMALE' : 'MALE';
      this.sexInput.showPicker = false;
    },
    userNameBlur() {
      // 不让它为""
      this.userInfoTemp.userName =
        this.userInfoTemp.userName.trim() === ""
          ? "匿名用户"
          : this.userInfoTemp.userName.trim();
    },
    afterRead(file) {
      console.log(file);
      let formData = new FormData();
      formData.append('avatar', file.file);

      this.userInfoTemp.userAvatar = file.content;
      this.userInfoTemp.avatarUpload = formData; // 头像上传的数据
      this.isUploadAvatar = true;
    },
  },
  computed: {
    ...mapState("m_user", ["userInfo"]),
    getSexChinese() {
      return this.userInfoTemp.sex === 'FEMALE' ? '男' : '女'
    }
  },
};
</script>

<style lang="scss" scoped>
.panel {
  position: relative;
  padding-left: 10px;

  .content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 0;
    color: rgb(68, 68, 68);

    .label {
      font-size: 14px;
    }

    .input-box {
      padding-right: 15px;
      text-align: right;
      font-size: 14px;
    }
  }

  &::after {
    content: "";
    display: block;
    width: 100%;
    height: 1px;
    background-color: #ccc;
  }
}

.van-cell {
  display: flex;
  justify-content: flex-end;
  padding: 0;
}
// 样式穿透
::v-deep .van-field__control {
  color: rgb(129, 129, 129) !important;
}
.van-cell::after {
  border: none;
}
::v-deep .van-nav-bar__content {
  height: 60px;
}
</style>
